const util = require('../util/util')
const Sequelize = require('sequelize')
const SequelizeModel = require('./SequelizeModel')
const errorConst = require('../const/error')
const commonConst = require('../const/common')

let MsgObj = SequelizeModel.define('nm_msg', {
  title: Sequelize.STRING,
  content: Sequelize.STRING,
  edit_times: Sequelize.INTEGER,
  created_at: {
    type: Sequelize.INTEGER,
    get () {
      let createdAt = this.getDataValue('created_at')
      return util.formatDateTime(createdAt * 1000)
    }
  },
  updated_at: {
    type: Sequelize.DATE,
    get () {
      let retInfo = ''
      let updatedAt = this.getDataValue('updated_at')
      if (updatedAt && typeof (updatedAt) === 'object') retInfo = updatedAt.toLocaleString()
      return retInfo
    }
  },
  status: Sequelize.INTEGER,
  user_id: Sequelize.INTEGER
}, {
  tableName: 'nm_msg',
  timestamps: false,
  freezeTableName: true
})

const exModel = {
  createByData: async data => {
    let retFlag = false
    if (!data.title || !data.user_id) {
      throw new Error(errorConst.msgAddNeedInfo)
    }
    data.content || (data.content = '')
    let msgModel = MsgObj
    let result = await msgModel.create({
      user_id: data.user_id,
      title: data.title,
      content: data.content,
      edit_time: 1,
      created_at: util.nowTime(),
      status: commonConst.statusCommon
    })
    console.log(result)

    if (result) {
      retFlag = true
    }
    return retFlag
  },
  updateByData: async data => {
    let retFlag = false
    if (!data.id) {
      throw new Error(errorConst.parameterError)
    }
    data.content || (data.content = '')
    let msgModel = MsgObj
    let result = await msgModel.update({
      title: data.title,
      content: data.content
    }, {
      where: {id: data.id}
    })

    if (result) {
      retFlag = true
    }
    return retFlag
  },
  getListByUserId: async userId => {
    let retList = []
    if (!userId) {
      return retList
    }

    retList = await MsgObj.findAll({
      where: {
        user_id: userId,
        status: commonConst.statusCommon
      },
      order: [
        ['updated_at', 'DESC'],
        ['id', 'DESC']
      ]
    })
    retList || (retList = [])
    retList.forEach(function (item, i) {
      item.content = util.subStr(util.stripHtml(item.content), 150)
      // console.log(item, i)
    })
    return retList
  },
  getInfoById: async id => {
    let retInfo = {}
    if (!id) {
      return retInfo
    }
    retInfo = await MsgObj.findOne({
      where: {
        id: id,
        status: commonConst.statusCommon
      }
    })
    retInfo || (retInfo = {})
    return retInfo
  }
}

module.exports = exModel
